<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" validate-trigger="submit" err-show-type="toast">
			<uni-forms-item label-width="200" name="username" label="用户名，不允许重复" v-show="false">
				<uni-easyinput placeholder="用户名，不允许重复"  v-model="formData.username" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="no" label="护工编号">
				<uni-easyinput placeholder="护工编号"  v-model="paramedic_profile.no" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="name" label="护工姓名">
				<uni-easyinput placeholder="护工姓名" v-model="paramedic_profile.name" />
			</uni-forms-item>
			 <uni-forms-item label-width="200" name="birthday" label="护工出生年月日">
				<el-date-picker
				      v-model="paramedic_profile.birthday"
				      type="date"
				      placeholder="护工出生年月日"
				      format="yyyy 年 MM 月 dd 日"
				       value-format="yyyy-MM-dd">
				</el-date-picker>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="id_card_no" label="护工身份证号">
				<uni-easyinput placeholder="护工身份证号" v-model="paramedic_profile.id_card_no" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="id_card_front" label="护工身份证正面">
				<cloud-image placeholder="护工身份证正面" v-model="paramedic_profile.id_card_front"></cloud-image>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="id_card_back" label="护工身份证反面">
				<cloud-image placeholder="护工身份证反面" v-model="paramedic_profile.id_card_back"></cloud-image>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="id_card_issue" label="护工身份证发证机关">
				<uni-easyinput placeholder="护工身份证发证机关" v-model="paramedic_profile.id_card_issue" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="id_card_start_date" label="护工身份证有效期始">
				<el-date-picker
					  v-model="paramedic_profile.id_card_start_date"
					  type="date"
					  placeholder="护工身份证有效期始"
					  format="yyyy 年 MM 月 dd 日"
					   value-format="yyyy-MM-dd">
				</el-date-picker>
			</uni-forms-item>
			 <uni-forms-item label-width="200" name="id_card_end_date" label="护工身份证有效期止">
				 <el-date-picker
				 	  v-model="paramedic_profile.id_card_end_date"
				 	  type="date"
				 	  placeholder="护工身份证有效期止"
				 	  format="yyyy 年 MM 月 dd 日"
				 	   value-format="yyyy-MM-dd">
				 </el-date-picker>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="zodiac" label="属相">
				<el-select v-model="paramedic_profile.zodiac" placeholder="请选择属相">
				    <el-option
				      v-for="(item,key) in formOptions.zodiacArr"
				      :key="key"
				      :label="item"
				      :value="item">
				    </el-option>
				  </el-select>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="constellation" label="星座">
				<el-select v-model="paramedic_profile.clan" placeholder="请选择星座">
				    <el-option
				      v-for="(item,key) in formOptions.constellationArr"
				      :key="key"
				      :label="item"
				      :value="item">
				    </el-option>
				</el-select>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="hometown" label="籍贯">
				<uni-easyinput placeholder="籍贯" v-model="paramedic_profile.hometown" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="clan" label="民族">
				<el-select v-model="paramedic_profile.clan" placeholder="请选择民族">
				    <el-option
				      v-for="(item,key) in formOptions.ethnicArr"
				      :key="key"
				      :label="item"
				      :value="item">
				    </el-option>
				  </el-select>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="education" label="学历">
				<el-select v-model="paramedic_profile.education" placeholder="请选择学历">
				    <el-option
				      v-for="(item,key) in formOptions.educationArr"
				      :key="key"
				      :label="item"
				      :value="item">
				    </el-option>
				  </el-select>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="address" label="地址">
				<uni-easyinput placeholder="地址" v-model="paramedic_profile.address" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="bank_card" label="银行卡照片">
				<cloud-image placeholder="银行卡照片" v-model="paramedic_profile.bank_card"></cloud-image>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="bank" label="开户银行">
				<uni-easyinput placeholder="开户银行" v-model="paramedic_profile.bank" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="bank_card_no" label="银行卡号">
				<uni-easyinput placeholder="银行卡号" v-model="paramedic_profile.bank_card_no" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="working_year" label="工作年限">
				<uni-easyinput placeholder="工作年限" v-model="paramedic_profile.working_year" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="certificates" label="专业证件">
				<uni-file-picker 
					v-model="uploadImgs.certificates" 
					fileMediatype="image" 
					mode="grid" 
					@select="select($event,'certificates')" 
					@progress="progress($event,'certificates')" 
					@success="success($event,'certificates')" 
					@fail="fail($event,'certificates')" 
				></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="examination" label="体检报告">
				<uni-file-picker
					v-model="uploadImgs.examination" 
					fileMediatype="image" 
					mode="grid" 
					@select="select($event,'examination')" 
					@progress="progress($event,'examination')" 
					@success="success($event,'examination')" 
					@fail="fail($event,'examination')" 
				></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="background_checks" label="背景调查">
				<el-input
				  type="textarea"
				  :rows="4"
				 placeholder="背景调查" v-model="paramedic_profile.background_checks">
				</el-input>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="photos" label="服务照片">
				<uni-file-picker 
				    v-model="uploadImgs.photos" 
				    fileMediatype="image" 
				    mode="grid" 
				   @select="select($event,'photos')"
				   @progress="progress($event,'photos')" 
				   @success="success($event,'photos')" 
				   @fail="fail($event,'photos')" 
				/>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="training_records" label="培训记录">
				<Training v-model="paramedic_profile.training_records"></Training>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="introduce" label="自我介绍">
				<el-input
				  type="textarea"
				  :rows="4"
				 placeholder="自我介绍"  v-model="paramedic_profile.introduce">
				</el-input>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="comment" label="考核团评语">
				<el-input
				  type="textarea"
				  :rows="4"
				 placeholder="考核团评语"  v-model="paramedic_profile.comment">
				</el-input>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="care_item" label="陪护内容">
				<eltags v-model="paramedic_profile.care_item"></eltags>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="arrangement" label="排班时间">
				<el-tag
				  :key="arran"
				  v-for="arran in paramedic_profile.arrangement"
				  closable
				  :disable-transitions="false"
				  @close="handleClose($event,arran)">
				  {{arran}}
				</el-tag>
				<el-date-picker 
				  type="datetime"
				  placeholder="选择日期"   value-format="yyyy-MM-dd H:m"
				  class="input-new-tag"
				  v-if="arranVisible"
				  v-model="arranValue"
				  ref="savearranInput"
				  @keyup.enter.native="handleArranConfirm"
				  @blur="handleArranConfirm"
				></el-date-picker>
				<el-button v-else class="button-new-tag" size="small" @click="arranVisible=true">+新增加</el-button>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="hospital" label="意向服务医院">
				<el-select v-model="paramedic_profile.hospital" multiple  placeholder="意向服务医院">
					<el-option v-for="(item, inx) in queryhospital" :key="inx" :label="item.name" :value="item._id">
					</el-option>
				</el-select>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="service" label="服务项">
				<uni-easyinput placeholder="服务项" v-model="paramedic_profile.service" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="score" label="评分">
				<uni-easyinput placeholder="评分" v-model="paramedic_profile.score" />
			</uni-forms-item>
			<uni-forms-item label-width="200" name="score_count" label="打分数">
				<uni-easyinput placeholder="打分数" v-model="paramedic_profile.score_count" />
			</uni-forms-item> 
			<uni-forms-item label-width="200" name="tags" label="标签">
				<eltags v-model="paramedic_profile.tags"></eltags>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="service_location" label="服务类别">
				<el-checkbox-group v-model="paramedic_profile.service_location">
				   <el-checkbox :value="'to_hospital'" label="医院护理">医院护理</el-checkbox>
				   <el-checkbox :value="'to_home'" label="到家护理">到家护理</el-checkbox>
				 </el-checkbox-group>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="service" label="服务项">
				<el-select v-model="paramedic_profile.service" multiple  placeholder="服务项">
					<el-option v-for="(item, inx) in queryService" :key="inx" :label="item.title" :value="item._id">
					</el-option>
				</el-select>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="plus" label="附加服务项">
				<el-select v-model="paramedic_profile.plus" multiple  placeholder="附加服务项">
					<el-option v-for="(itemAttr, inxx) in queryServiceAttr" :key="inxx" :label="itemAttr.name" :value="itemAttr._id">
						<el-tooltip class="item" effect="dark" :content="itemAttr.desc" placement="right-start">
							<span style="float: left">{{ itemAttr.name }}</span>
						</el-tooltip>
					</el-option>
				</el-select>
			</uni-forms-item>
			<uni-forms-item label-width="200" name="work_status" label="工作状态">
				<el-radio  v-model="paramedic_profile.work_status" :label="true">上班</el-radio>
				 <el-radio v-model="paramedic_profile.work_status" :label="false">下班</el-radio>
			</uni-forms-item>
			 <uni-forms-item label-width="200" name="location" label="用户位置信息">
				 <block v-if="formData.location>0">经度：{{formData.location.coordinates[0]}}<br>纬度：{{formData.location.coordinates[1]}}</block>
				 <button type="primary" class="uni-button" @click="handleLocation">选择</button>
			 </uni-forms-item>
			<view class="uni-button-group"><button type="primary" class="uni-button" @click="submit">提交</button>
			<navigator open-type="navigateBack" style="margin-left: 15px;"><button style="width: 100px;" class="uni-button">返回</button></navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
import uniFilePicker from '@/components/uni-file-picker/uni-file-picker'
import eltags from '@/components/eltags.vue'
import Training from './components/Training.vue'
import { validator } from '../../js_sdk/validator/uni-id-users.js';
import commonData from '@/common/common.json'

const db = uniCloud.database();
const dbCollectionName = 'uni-id-users';

function getValidator(fields) {
	let reuslt = {};
	for (let key in validator) {
		if (fields.indexOf(key) > -1) {
			reuslt[key] = validator[key];
		}
	}
	return reuslt;
}

export default {
	components: {
		eltags,Training,uniFilePicker
	},
	data() {
		return {
			queryService:[],
			queryhospital:{},
			certificates:[],
			arranVisible:false,
			arranValue:'',
			inputVisible: false,
			inputValue: '',
			location:{},
			paramedic_profile: {
				plus:[],
				no: '',
				name: '',
				birthday: '',
				id_card_no: '',
				id_card_front: '',
				id_card_back: '',
				id_card_issue: '',
				id_card_start_date: '',
				id_card_end_date: '',
				zodiac: '',
				constellation: '',
				hometown: '',
				clan: '',
				education: '',
				address: '',
				bank_card: '',
				bank: '',
				bank_card_no: '',
				working_year: '',
				examination: [],
				background_checks: '',
				certificates: [],
				introduce: '',
				comment: '',
				photos: [],
				care_item: [],
				training_records: [],
				arrangement: [],
				hospital: '',
				service: '',
				score: '',
				score_count: '',
				tags: [],
				service_location:[],
				work_status: 'false'
			},
			formData: {
				username: '',
				nickname: '',
				gender: '',
				status: '',
				mobile: '',
				mobile_confirmed: '',
				email: '',
				email_confirmed: '',
				avatar: '',
				department_id: '',
				role: [],
				wx_unionid: '',
				wx_openid: { 'app-plus': '', 'mp-weixin': '' },
				ali_openid: '',
				apple_openid: '',
				comment: '',
				realname_auth: {
					type: '',
					auth_status: '',
					auth_date: '',
					real_name: '',
					identity: '',
					id_card_front: '',
					id_card_back: '',
					in_hand: '',
					license: '',
					contact_person: '',
					contact_mobile: '',
					contact_email: ''
				},
				register_date: '',
				register_ip: '',
				last_login_date: '',
				last_login_ip: '',
				token: '',
				inviter_uid: '',
				my_invite_code: '',
				//location: []
			},
			formOptions: {
				ethnicArr:commonData.ethnic,
				constellationArr:commonData.constellation,
				educationArr:commonData.education,
				zodiacArr:commonData.zodiac,
				sex_localdata: ['男', '女']
			},
			rules: {
				...getValidator([
					'paramedics_id',
					'type',
					'tel',
					'avatar',
					'name',
					'sex',
					'age',
					'level',
					'exp_year',
					'tags',
					'identity_no',
					'identity_img',
					'zodiac',
					'constellation',
					'native_place',
					'nation',
					'education',
					'examination',
					'background_checks',
					'certificates',
					'introduce',
					'comment',
					'photos',
					'care_item',
					'training_records',
					'arrangement'
				])
			},
			uploadImgs:{
				certificates:[],
				examination:[],
				photos:[]
			},
			queryServiceAttr:[]
		};
	},
	onLoad(e) {
		this.hospitalList();
		this.serviceList();
		this.serviceAttr()
	},
	onReady() {
		this.$refs.form.setRules(this.rules);
	},
	methods: {
		//获取附加服务项
		serviceAttr(){
			const that=this
			db.collection('attach_services')
				.field('_id,name,type,desc')
				.get()
				.then(res => {
					let resLi=[]
					const data = res.result.data;
					that.queryServiceAttr=data
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		//服务套餐
		serviceList(){
			const that=this
			db.collection('services')
				.field('_id,title,level')
				.get()
				.then(res => {
					let resLi=[]
					const data = res.result.data;
					that.queryService=data
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		//医院 
		hospitalList(){
			const that=this
			db.collection('hospitals')
				.field('_id,name,logo')
				.get()
				.then(res => {
					const data = res.result.data;
					if (data) {
						let resLi=[]
						data.forEach(item=>{
							resLi[item._id]=item.name
						})
					}
					that.queryhospital=data
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		handleArranConfirm(){
			let arranValue = this.arranValue;
			if (arranValue) {
				let tmpArranValue=this.paramedic_profile.arrangement
			    tmpArranValue.push(arranValue);
			}
			this.arranVisible = false;
			this.arranValue = '';
		},
		handleClose(tag,filed) {
			console.log(filed)
		   this.paramedic_profile[filed].splice(this.dynamicTags.indexOf(tag), 1);
		},
		showInput() {
			this.inputVisible = true;
			this.$nextTick(_ => {
			  this.$refs.saveTagInput.$refs.input.focus();
			});
		},
		handleInputConfirm() {
			let inputValue = this.inputValue;
			if (inputValue) {
				let tmpTags=this.paramedic_profile.tags
				console.log(tmpTags)
			  tmpTags.push(inputValue);
			}
			this.inputVisible = false;
			this.inputValue = '';
		},
		/**
		 * 触发表单提交
		 */
		submit() {
			const taht=this
			uni.showLoading({
				mask: true
			});
			this.$refs.form
				.validate()
				.then(res => {
					this.formData.paramedic_profile=this.paramedic_profile
					const tmpFormData=this.formData
					console.log('_______',this.formData)
					return false;
					this.submitForm(this.formData);
				})
				.catch(errors => {
					uni.hideLoading();
				});
		},

		submitForm(value) {
			value.status=0
			value.role=["paramedic"]
			// 使用 clientDB 提交数据
			db.collection(dbCollectionName)
				.add(value)
				.then(res => {
					uni.showToast({
						icon: 'none',
						title: '新增成功'
					});
					this.getOpenerEventChannel().emit('refreshData');
					setTimeout(() => uni.navigateBack(), 500);
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		/**
		 * 获取表单数据
		 * @param {Object} id
		 */
		getDetail(id) {
			uni.showLoading({
				mask: true
			});
			db.collection(dbCollectionName)
				.doc(id)
				.field(
					'_id,username,sbile_confirmed,email,email_confirmed,avatar,department_id,role,wx_unionid,wx_openid,ali_openid,apple_openid,comment,realname_auth,register_date,register_ip,last_login_date,last_login_ip,token,inviter_uid,my_invite_code,paramedic_profile,location'
				)
				.get()
				.then(res => {
					const data = res.result.data[0];
					if (data) {
						this.paramedic_profile=data.paramedic_profile
						if(!data.paramedic_profile.training_records){
							this.paramedic_profile.training_records=[]
						}
						if(data.paramedic_profile.certificates){
							let ar=[]
							data.paramedic_profile.certificates.forEach(item=>{
								ar.push({
									'src':item,
									'path':item,
									'name':item,
									'type':'img'
								})
							})
							this.uploadImgs.certificates=ar
						}
						if(data.paramedic_profile.examination){
							let ar=[]
							data.paramedic_profile.examination.forEach(item=>{
								ar.push({
									'src':item,
									'path':item,
									'name':item,
									'type':'img'
								})
							})
							this.uploadImgs.examination=ar
						}
						if(data.paramedic_profile.photos){
							let ar=[]
							data.paramedic_profile.photos.forEach(item=>{
								ar.push({
									'src':item,
									'path':item,
									'name':item,
									'type':'img'
								})
							})
							this.uploadImgs.photos=ar
						}
						this.formData = data;
					}
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		handleLocation(){
			const that=this
			uni.chooseLocation({
				keyword:'云南省昆明市',
				success: function(res) {
					that.addressName=res.name+'('+res.longitude+"，"+ res.latitude+'）'
					that.formData.location={
						"coordinates": [res.longitude, res.latitude ],
						"type": "Point"
						}
				}
			});
		},
		// 获取上传状态
		select(e,filed){
			console.log('选择文件：',e)
		},
		// 获取上传进度
		progress(e,filed){
			console.log('上传进度：',e)
		},
		// 上传成功
		success(e,filed){
			let tmpLIst=[];
			let resArr=[];
			e.tempFiles.forEach(item=>{
				resArr.push(item.url);
				tmpLIst.push({path:item.url,img:item.url,type:item.name})
			})
			this.uploadImgs[filed]=tmpLIst
			this.paramedic_profile[filed]=resArr
		},

		// 上传失败
		fail(e){
			console.log('上传失败：',e)
		}
	}
};
</script>

<style scoped>
.uni-forms-item__label {
	width: 200px !important;
}
.uni-container {
	padding: 15px;
}

.uni-input-border,
.uni-textarea-border {
	width: 100%;
	font-size: 14px;
	color: #666;
	border: 1px #e5e5e5 solid;
	border-radius: 5px;
	box-sizing: border-box;
}

.uni-input-border {
	padding: 0 10px;
	height: 35px;
}

.uni-textarea-border {
	padding: 10px;
	height: 80px;
}

.uni-button-group {
	margin-top: 50px;
	display: flex;
	justify-content: center;
}

.uni-button {
	width: 184px;
	padding: 12px 20px;
	font-size: 14px;
	border-radius: 4px;
	line-height: 1;
	margin: 0;
}
</style>
